﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using br.com.SistemaChamados.Controller;
using br.com.SistemaChamados.Model;
using br.com.SistemaChamados.Controller.Common;
using br.com.SistemaChamados.Model.Common;
using br.com.SistemaChamados.Enum;

public partial class Pages_PersonUpdate : System.Web.UI.Page
{
    private const string SESSION_UPDATE_USER = "userToUpdate";
    private const string SESSION_UPDATE_USER_ID = "UserIdToUpdate";

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            GetUserFromSession();
            FillDdlUnit();
            FillData();
        }
    }
    private void FillDdlUnit()
    {
        UnitController unitController = new UnitController();
        ddlUnit.DataSource = unitController.GetUnits();
        ddlUnit.DataTextField = "Name";
        ddlUnit.DataValueField = "Id";
        ddlUnit.DataBind();
        ddlUnit.Items.Insert(0, "Selecione");
    }

    private void GetUserFromSession()
    {
        User user = new User();
        user.Id = Convert.ToInt32(Session[SESSION_UPDATE_USER_ID]);
        UserController Controller = new UserController();
        User returnedUser = new User();
        try
        {
            returnedUser = Controller.GetUser(user);
            if (returnedUser != null)
            {
                txbName.Text = returnedUser.Name;
                txbEMail.Text = returnedUser.EMail;
                Session[SESSION_UPDATE_USER] = returnedUser;
            }
        }
        catch (Exception ex)
        {
            Response.Write(@"<script language='javascript'>alert('Ocorreu um erro no carregamento da tela: <br>" + ex.Message +
                               ".');</script>");
        }
    }

    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        if (ddlSector.SelectedIndex == 0)
        {
            Response.Write(@"<script language='javascript'>alert('Selecione um setor');</script>");
            ddlSector.Focus();
        }
        else
        {
            if (ddlUnit.SelectedIndex == 0)
            {
                Response.Write(@"<script language='javascript'>alert('Selecione uma unidade');</script>");
                ddlUnit.Focus();
            }
            else
            {
                User updatedUser = new User();
                updatedUser.Sector = new Sector();
                object objectFromSession = Session[SESSION_UPDATE_USER_ID];
                updatedUser.Id = Convert.ToInt32(objectFromSession);
                Sector sector = new Sector();
                updatedUser.Name = txbName.Text;
                updatedUser.EMail = txbEMail.Text;
                updatedUser.Sector.Id = Convert.ToInt32(ddlSector.SelectedValue);
                User userFromSession = (User)Session[SESSION_UPDATE_USER];
                if (chbEditPassword.Checked)
                {
                    if (txbOldPassword.Text == userFromSession.Password)
                    {
                        updatedUser.Password = txbNewPassword.Text;
                        TryUpdate(updatedUser);
                    }
                    else
                    {
                        Response.Write(@"<script language='javascript'>alert('Senha incorreta !');</script>");
                    }
                }
                else
                {
                    updatedUser.Password = userFromSession.Password;
                    TryUpdate(updatedUser);
                }
            }
        }
        
    }

    private void TryUpdate(User updatedUser)
    {
        UserController Controller = new UserController();
        try
        {
            if (Controller.UpdateUser(updatedUser) == EnumGenericState.GENERIC_STATE_SUCCESS)
            {
                Response.Write(@"<script language='javascript'>alert('Pessoa Corrigida com Sucesso!');</script>");
                ClearFields();
            }
            else
            {
                Response.Write(@"<script language='javascript'>alert('Ocorreu um erro durante a correção, por favor tente novamente!');</script>");
            }
        }
        catch (Exception ex)
        {
            Response.Write(@"<script language='javascript'>alert('Ocorreu um erro na correção: <br>" + ex.Message +
                               ".');</script>");
            updatedUser = null;
        }
        finally
        {
            Response.Redirect("UserMain.aspx");
            ClearSession();
        }
    }

    private void ClearSession()
    {
        Session.Remove("id");
        Session.Remove("userToUpdate");
    }

    private void FillData()
    {
        string id = Session["UserIdToUpdate"].ToString();
        User user = new User();
        UserController userController = new UserController();
        user.Id = Convert.ToInt32(id);
        user = userController.GetUser(user);
        Sector sector = new Sector();
        SectorController sectorController = new SectorController();
        sector.Id = user.Sector.Id;
        sector = sectorController.GetSector(sector);
        try
        {
            MatchDdlUnitValue(sector);
            FillDdlSector();
            MatchDdlSectorValue(sector);
            txbName.Text = Convert.ToString(user.Name);
            txbEMail.Text = Convert.ToString(user.EMail);
        }
        catch (Exception ex)
        {
            Response.Write(@"<script language='javascript'>alert('Ocorreu um erro no carregamento dos valores: <br>" + ex.Message +
                               ".');</script>");
        }
    }

    private void MatchDdlSectorValue(Sector sector)
    {
        ListItem listSector = ddlSector.Items.FindByValue(Convert.ToString(sector.Id));
        for (int i = 0; i < ddlSector.Items.Count; i++)
        {
            ddlSector.Items[i].Selected = false;
        }
        if (listSector != null)
        {
            listSector.Selected = true;
        }
        else
        {
            ddlSector.Items[0].Selected = true;
        }
    }

    private void MatchDdlUnitValue(Sector sector)
    {
        ListItem listUnit = ddlUnit.Items.FindByValue(Convert.ToString(sector.Unit.Id));

        for (int i = 0; i < ddlUnit.Items.Count; i++)
        {
            ddlUnit.Items[i].Selected = false;
        }
        if (listUnit != null)
        {
            listUnit.Selected = true;
        }
        else
        {
            ddlUnit.Items[0].Selected = true;
        }
    }

    private void FillDdlSector()
    {
        SectorController sectorController = new SectorController();
        Sector sector = new Sector();
        br.com.SistemaChamados.Model.Unit unit = new br.com.SistemaChamados.Model.Unit();
        if (Convert.ToInt32(ddlUnit.SelectedIndex) != 0)
        {
            unit.Id = Convert.ToInt32(ddlUnit.SelectedValue);
            sector.Unit = unit;
            ddlSector.DataSource = sectorController.ListSectorByUnit(sector);
            ddlSector.DataTextField = "Description";
            ddlSector.DataValueField = "Id";
            ddlSector.DataBind();
            ddlSector.Items.Insert(0, "Selecione");
        }
        else
        {
            ClearDdlSector();
        }
    }

    private void ClearDdlSector()
    {
        for (int i = 0; i < ddlSector.Items.Count; i++)
        {
            ddlSector.Items[i].Selected = false;
        }
        ddlSector.Items[0].Selected = true;
        ddlSector.DataSource = "";
        ddlSector.DataBind();
    }


    private void ClearFields()
    {
        txbName.Text = "";
        txbEMail.Text = "";
        txbNewPassword.Text = "";
        txbPasswordValidate.Text = "";
        txbName.Focus();
    }

    protected void chbEditPassword_CheckedChanged(object sender, EventArgs e)
    {
        if (chbEditPassword.Checked)
        {
            txbNewPassword.Enabled = true;
            txbOldPassword.Enabled = true;
            txbPasswordValidate.Enabled = true;
            passwordValidator.Enabled = true;
            newPasswordValidator.Enabled = true;
            ComparePassword.Enabled = true;
        }
        else
        {
            txbOldPassword.Enabled = false;
            txbNewPassword.Enabled = false;
            txbPasswordValidate.Enabled = false;
            passwordValidator.Enabled = false;
            newPasswordValidator.Enabled = false;
            ComparePassword.Enabled = false;
        }
    }
    protected void ddlUnit_SelectedIndexChanged(object sender, EventArgs e)
    {
        FillDdlSector();
    }
}
